using net_work.Common.Request;
using net_work.Common.Result;
using net_work.Data.DTO.Hmw;
using net_work.Data.Entity.Hmw;
using net_work.IRepository.Hmw;
using net_work.IService.Hmw;

namespace net_work.Service.Hmw;

public class HomeworkQuestionService(
    IHomeworkQuestionRepository homeworkQuestionRepository,
    IBankQuestionRepository bankQuestionRepository,
    IHomeworkRepository homeworkRepository)
    : IHomeworkQuestionService
{
    public Task<PagedResult<HomeworkQuestion>> GetHomeworkQuestionsPagedAsync(PagedRequest request)
    {
        return homeworkQuestionRepository.GetPagedAsync(request);
    }

    public Task<HomeworkQuestion?> SelectByIdAsync(long homeworkQuestionId)
    {
        return homeworkQuestionRepository.GetByIdAsync(homeworkQuestionId);
    }

    public async Task<int> InsertHomeworkQuestion(HomeworkQuestionAddRequest homeworkQuestionAddRequest)
    {
        var homework = await homeworkRepository.GetByIdAsync(homeworkQuestionAddRequest.HomeworkId);
        if (homework == null)
        {
            return -1;
        }

        var bankQuestion = await bankQuestionRepository.ValidateByList(homeworkQuestionAddRequest.BankQuestionIds);
        if (!bankQuestion)
        {
            return -1;
        }

        return await homeworkQuestionRepository.InsertAsync(homeworkQuestionAddRequest);
    }

    public async Task<int> UpdateHomeworkQuestion(HomeworkQuestionUpdateRequest homeworkQuestionUpdateRequest)
    {
        if (homeworkQuestionUpdateRequest.Id <= 0)
        {
            return -1;
        }

        var homework = await homeworkRepository.GetByIdAsync(homeworkQuestionUpdateRequest.HomeworkId);
        if (homework == null)
        {
            return -1;
        }

        var bankQuestion = await bankQuestionRepository.GetByIdAsync(homeworkQuestionUpdateRequest.BankQuestionId);
        if (bankQuestion == null)
        {
            return -1;
        }

        return await homeworkQuestionRepository.UpdateAsync(homeworkQuestionUpdateRequest) ? 1 : -1;
    }

    public async Task<int> DeleteHomeworkQuestionByIds(List<long> ids)
    {
        return await homeworkQuestionRepository.DeleteByIdsAsync(ids) ? 1 : -1;
    }
}